﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Security.Cryptography;
using System.Text;

public partial class Manager_User_AddCustomer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
        Ajax.Utility.RegisterTypeForAjax(typeof(Manager_User_AddCustomer));
        if (!IsPostBack)
        {
            if (Request.QueryString["Type"] == "NewUser")
            {
                lblTextTiltle.Text = "Cập nhật thành viên";
                BindAuthorityList();
                trAut.Visible = true;
            }
         
            BindPlace();
            Get_BirthDay(drlDay, 1, 31);
            Get_BirthDay(drlMonth, 1, 12);
            Get_BirthDay(drlYear, 1930, System.DateTime.Now.Year);

            BindData();
            //RefRules.ErrorMessage = "Bạn chưa đồng ý với những quy định của " + System.Configuration.ConfigurationManager.AppSettings["AppName"];
            /*lblRules.Text = "Tôi đã đọc và đồng ý với những quy định của " + System.Configuration.ConfigurationManager.AppSettings["AppName"];
            lblRules.Attributes.Add("onclick", "javascript:window.open('../../Member/Register/Rules.aspx','winRules','status=1,menu=0,scrollbars=1');");
            lblRules.Attributes.Add("onmouseover", "javascript:this.className='lbl_OverAgree';");
            lblRules.Attributes.Add("onmouseout", "javascript:this.className='lbl_OutAgree';");*/
        }
    }

    private void BindAuthorityList()
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlAut.DataSource = cls.Get_shr_AuthorityNoneProc().Tables[0];
        ddlAut.DataTextField = "AutNm";
        ddlAut.DataValueField = "AutID";
        ddlAut.DataBind();
        item.Text = "-- Chọn quyền hạn --";
        item.Value = "0"; //
        ddlAut.Items.Insert(0, item);



    }
   
    private void BindData()
    {
        if (Request.QueryString["UserID"] != "" && Request.QueryString["UserID"] != null)
        {
            chkAutoPass.Text = "Giữ lại mật khẩu cũ";

            clsWebShop cls = new clsWebShop();
            DataTable dt = cls.Get_CustomerByUserIDNoneProc(Request.QueryString["UserID"]).Tables[0];
            if (dt.Rows.Count > 0)
            {

                hidEmail.Text = "aaa";
                hidUser.Text = "aaa";

                txtName.Text = dt.Rows[0]["CusNm"].ToString().Trim();
                txtUser.Text = dt.Rows[0]["UserNm"].ToString().Trim();
                txtEmail.Text = dt.Rows[0]["Email"].ToString().Trim();
                txtPhone.Text = dt.Rows[0]["Phone"].ToString().Trim();
                txtAddress.Text = dt.Rows[0]["Address"].ToString().Trim();

                if (dt.Rows[0]["PlaceID"].ToString() != "")
                {
                    
                    try
                    {
                        ddlPlace.SelectedItem.Selected = false;
                        ddlPlace.Items.FindByValue(dt.Rows[0]["PlaceID"].ToString()).Selected = true;
                    }
                    catch { }
                }
                txtTaxNo.Text = dt.Rows[0]["TaxNo"].ToString().Trim();

                if (dt.Rows[0]["Sex"].ToString() != "")
                {
                    try
                    {
                        DrlSex.SelectedItem.Selected = false;
                        DrlSex.Items.FindByValue(dt.Rows[0]["Sex"].ToString()).Selected = true;
                    }
                    catch { }
                }

                if (dt.Rows[0]["BirthDay"].ToString() != "")
                {
                     try
                    {
                    drlDay.SelectedItem.Selected = false;
                    drlDay.Items.FindByValue(dt.Rows[0]["BirthDay"].ToString().Substring(6, 2)).Selected = true;
                    drlMonth.SelectedItem.Selected = false;
                    drlMonth.Items.FindByValue(dt.Rows[0]["BirthDay"].ToString().Substring(4, 2)).Selected = true;
                    drlYear.SelectedItem.Selected = false;
                    drlYear.Items.FindByValue(dt.Rows[0]["BirthDay"].ToString().Substring(0, 4)).Selected = true;
                }
                catch { }
                }

                if (Request.QueryString["Type"] == "NewUser")
                {
                    try
                    {
                        ddlAut.SelectedItem.Selected = false;
                        ddlAut.Items.FindByValue(dt.Rows[0]["AutID"].ToString()).Selected = true;
                    }
                    catch { }
                }


            }
        }
    }

    private void BindPlace()
    {
        clsWebShop cls = new clsWebShop();
        ddlPlace.DataSource = cls.Get_PlaceNoneProc();
        ddlPlace.DataTextField = "PlaceNm";
        ddlPlace.DataValueField = "PlaceID";
        ddlPlace.DataBind();

    }

    private void Get_BirthDay(DropDownList ddl, int first, int last)
    {

        for (int i = first; i <= last; i++)
        {
            if (i < 10)
                ddl.Items.Add("0" + i);
            else
                ddl.Items.Add(i.ToString());

        }

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        string UserID = "0";
        string strPassEncry = "", strPass = "",strAut="0";
        RijndaelManaged mobjCryptoService = new RijndaelManaged();
        EncrypKey clsEncryp = new EncrypKey(mobjCryptoService);
       
        if (Request.QueryString["Type"] == "NewUser")
        {
            strAut = ddlAut.SelectedValue;
        }
        if (Request.QueryString["UserID"] != "" && Request.QueryString["UserID"] != null)
        {
            UserID = Request.QueryString["UserID"];
            strPass = txtPassword.Text;
        }
        else
        {
            if (chkAutoPass.Checked == true)
            {
                strPass = RandomString(5).ToString().ToLower();
            }
            else
            {
                strPass = txtPassword.Text;
            }
        }

        strPassEncry = clsEncryp.Encrypting((strPass), System.Configuration.ConfigurationManager.AppSettings["EncrypKey"]);
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();


        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("UserID", UserID);
        msg.CreateFirstNode("AutID", strAut);
        msg.CreateFirstNode("CusNm", txtName.Text);
        msg.CreateFirstNode("UserNm", txtUser.Text);
        msg.CreateFirstNode("Password", strPassEncry);
        msg.CreateFirstNode("AccountID", "");
        msg.CreateFirstNode("TaxNo", txtTaxNo.Text);
        msg.CreateFirstNode("Address", txtAddress.Text);
        msg.CreateFirstNode("PlaceID", ddlPlace.SelectedValue);
        msg.CreateFirstNode("BirthDay", drlYear.SelectedItem.Text + drlMonth.SelectedItem.Text + drlDay.SelectedItem.Text);
        msg.CreateFirstNode("Phone", txtPhone.Text);
        msg.CreateFirstNode("Sex", DrlSex.SelectedValue);
        msg.CreateFirstNode("Email", txtEmail.Text);
        msg.CreateFirstNode("Status", "N");
        msg.CreateFirstNode("Rate", "0");
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        string strReturn = cls.Ins_Upd_shr_User(msg.GetXmlStr.ToString());
        msg = new PccMsg(strReturn);
        string strErr = msg.Query("strOutput");
        string strOutUserID = msg.Query("strOutUserID");


        if (strErr == "0" && strOutUserID != "")
        {

            /*==========================SEND MAIL====================================*/
            if (txtEmail.Text.Trim()!="")
            {
                string HTML = "Xin chào " + txtName.Text + "!<br>";
                HTML += "Cảm ơn bạn đã sử dụng dịch vụ của chúng tôi. Dưới đây là thông tin tài khoản bạn đã đăng ký tại website của chúng tôi<br>";
                HTML += "- Tên đăng nhập: " + txtUser.Text + "<br>";
                HTML += "- Địa chỉ e-mail: " + txtEmail.Text + "<br>";
                HTML += "- Mật khẩu: " + strPass + "<br><br><br><br><br><br>";
                HTML += "Thank you to  my website: <a  href='http://" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"].ToString() + "'>" + System.Configuration.ConfigurationManager.AppSettings["AppAddress"].ToString() + "</a>";



                clsCom.Send_AppEmail(System.Configuration.ConfigurationManager.AppSettings["InfoMail"].ToString(), txtEmail.Text, System.Configuration.ConfigurationManager.AppSettings["InfoMail"].ToString() + ";" + System.Configuration.ConfigurationManager.AppSettings["WebMail"].ToString(), "Thông tin tài khoản khách hàng", HTML);
            }
            /*==============================================================*/

            if (Request.QueryString["Type"] == "NewCus" || Request.QueryString["Type"] == "NewUser")
            {
                if (Request.QueryString["UserID"] != "" && Request.QueryString["UserID"] != null)
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Bảo lưu thành công!!!'); window.location.href='Customer.aspx?CodeID=" + Request.QueryString["CodeID"] + "&Type=" + Request.QueryString["Type"] + "'</script>");
                }
                else
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Bảo lưu thành công!!!. Tiếp tục đăng ký mới'); window.location.href='AddCustomer.aspx?CodeID=" + Request.QueryString["CodeID"] + "&Type=" + Request.QueryString["Type"] + "'</script>");
                }


            }
            else
            {
                Response.Write("<script>window.opener.fnChooseUser('" + strOutUserID + "'); window.close();</script>");
            }

        }
    }

    private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }

        return builder.ToString();
    }
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string AjaxCheckUser(string value, string ExcUserID)
    {
        string flag = "no";
        clsWebShop cls = new clsWebShop();
        DataTable dt = new DataTable();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("UserNm", value.Trim());
        msg.CreateFirstNode("ExcUserID", ExcUserID);
        dt = cls.Get_shr_UserByUserNm(msg.GetXmlStr.ToString()).Tables[0];
        if (dt.Rows.Count > 0)
            flag = "yes";
        return flag;
    }
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string AjaxCheckEmail(string value, string ExcUserID)
    {
        string flag = "no";
        clsWebShop cls = new clsWebShop();
        DataTable dt = new DataTable();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("ExcUserID", ExcUserID);
        msg.CreateFirstNode("Email", value.Trim());
        dt = cls.Get_shr_UserByUserEmail(msg.GetXmlStr.ToString()).Tables[0];
        if (dt.Rows.Count > 0)
            flag = "yes";
        return flag;
    }
    private void ReturnPage()
    {
        Response.Redirect("Customer.aspx?CodeID=" + Request.QueryString["CodeID"] + "&Type="+Request.QueryString["Type"]+"");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["Type"] == "Admin")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>window.close();</script>");
        }
        else
        {
            ReturnPage();
        }
    }
}
